<template>
  <div id="person-list" class="app-container">
    <p style="color: red">
      (<span class="big-number">注： </span>当前界面非开发者禁止做操作！)
      <span class="color-drak">*排序：值越大越靠上</span>
    </p>
    {{ editData }}
    <div style="margin-bottom: 12px">
      <el-button type="primary" @click="addMenu"> 主节点添加 </el-button>
    </div>

    <div
      class="widget-tree black-bg2 size16 max-height-auto scrollbar-slinder"
      style="width: 60%;padding-bottom:50px"
    >
      <el-tree
        ref="treeNode"
        :data="treeList"
        :default-expanded-keys="['#']"
        :props="defaultProps"
        :render-after-expand="true"
        :expand-on-click-node="false"
        class="black-bg color-white full-width"
        style="padding: 10px"
        node-key="id"
      >
        <div slot-scope="{ node, data }" class="full-width">
          <div class="flex justify-between full-width align-center">
            <span>{{ node.label }}</span>
            <div>
              <el-button
                type="primary"
                size="mini"
                plain
                @click="showEdit(data, 0)"
              >
                子节点添加
              </el-button>
              <el-button type="primary" size="mini" @click="showEdit(data, 1)">
                编辑
              </el-button>
              <el-button type="danger" size="mini" @click="delectMenu(data)">
                删除
              </el-button>
            </div>
          </div>
        </div>
      </el-tree>
      <!-- {{ treeList }} -->
      <!-- <el-cascader
        filterable
        placeholder="试试搜索：手机"
        v-model="catelogPath"
        :options="treeList"
        :props="props"
      ></el-cascader> -->
    </div>

    <back-to-top
      :visibility-height="300"
      :back-position="0"
      transition-name="fade"
    />
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      v-dialogDrag
      :visible.sync="editDialog"
      v-loading="editLoading"
      custom-class="widget-dialog widget-form center no-margin color-white black-bg2"
      title="编辑菜单"
    >
      <form-create
        v-model="editFormInstance"
        :value.sync="editData"
        :rule="editRule"
        :option="editOptions"
      >
        <template slot="row">
          <div class="color-active">afsdfafsdfafsdfafsdf</div>
        </template>
      </form-create>
      <template slot="footer">
        <el-button size="mini" type="primary" @click="update(editData)"
          >提交</el-button
        >
        <el-button size="mini" @click="reset">重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  sysGetMenuList as searchApi, //获取列表的api
  sysAddMenu as addApi, //新增数据的api
  sysEditMenu as updateApi, //更新、新增数据的api
  sysDeleteMenu as removeApi //删除数据的api
  //   sysGetRoleByUserId as detailApi, //详情api
} from "@/api";
import { editRule, searchRule } from "@/formRules/MenuRules";
import { editFormOptions, getData } from "@/formRules";
import checkPermission from "@/utils/permission";
import { isDev } from "@/configurations.js";
import { translateDataToTree } from "@/utils/parentSon";
import { topoList } from "@/constants/topo";

export default {
  name: "PersonList",
  configurations: {
    title: "角色管理",
    isDefault: true,
    show: true
  },
  data() {
    return {
      editRule: editRule(),
      listData: [],
      searchRule: searchRule(),
      searchData: {}, //搜索表单数据
      editFormInstance: {},
      editData: {},
      editOptions: editFormOptions(),
      editDialog: false,
      editLoading: false,
      listLoading: false,
      toReview: 0,
      pageInfo: {
        page: 1,
        size: 500,
        total: 0
      },
      permissionList: [], //权限列表
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      topoList: translateDataToTree(topoList()),
      topoDialog: false,
      topoLoading: false,
      topoShowList: [],
      catelogPath: "",
      props: {
        value: "id",
        label: "menuName",
        children: "children"
      }
    };
  },
  // 在路由导航进来之前检查权限
  beforeRouteEnter(from, to, next) {
    const permissionList = checkPermission(to.path);
    if (permissionList.length) {
      next(vm => {
        vm.permissionList = permissionList;
      });
      return;
    }
    next({
      name: "403"
    });
  },
  mounted() {
    this.topoList = this.topoList.filter((e, index) => index == 0);
    console.log(this.topoList);
    this.getList(this.searchData, this.pageInfo);
  },
  computed: {
    // 根据获取的权限列表此处返回各个权限的显示与否
    permissions() {
      return ["edit", "remove", "add"].reduce((pre, cur) => {
        pre[cur] = isDev ? true : this.permissionList.includes(cur);
        return pre;
      }, {});
    },
    treeList() {
      let tree = [];
      let data = translateDataToTree(this.listData);
      if (data.length) {
        tree.push(data[0]);
      } else {
        tree = [];
      }
      return data;
    }
  },
  methods: {
    checkReview() {
      searchApi({
        isLock: 1,
        hasOpenid: 1,
        name: "",
        position: "",
        pageSize: 1000,
        pageNo: 1
      }).then(({ data }) => {
        this.toReview = data.dataList.length;
      });
    },
    searchReview() {
      this.searchData.isLock = 1;
      this.searchData.hasOpenid = 1;
      this.searchData.name = "";
      this.searchData.position = "";
      this.getList(this.searchData, this.pageInfo);
    },

    /**
     * @name 查询列表
     * @param {Object} query 查询参数，一般为this.searchData
     * @param {Object} pageInfo 页面参数，包括pageSize和pageNo
     * @description 调用成功则刷新listData
     */
    getList(query, pageInfo) {
      this.listLoading = true;
      const queryParam = {
        ...pageInfo,
        ...query
      };
      searchApi(queryParam)
        .then(({ code, data }) => {
          console.log(data);
          if (code == 200) {
            this.listData = data.list;
            this.listData.forEach(element => {
              if (element.parent) {
                element.parentId = Number(element.parent);
              } else {
                element.parentId = element.parent;
              }
            });
            this.pageInfo.total = data.total;
          }
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    /**
     * @name 编辑表单
     * @param {Object} row 表单数据，新增时为空
     * @param {Object} val 0为新增 1为修改
     * @description 调用成功打开表单对话框
     */
    showEdit(row, val) {
      console.log("row", row);
      console.log(this.catelogPath);
      if (!val) {
        this.editData = getData(editRule());
        this.editDialog = true;
        this.editData.parent = row.id;
      } else {
        // detailApi({ id: row.id }).then((res) => {
        //   const { data } = res;
        this.editData = row;
        if (this.editData.components && this.editData.layout == "Dashboard") {
          let comData = JSON.parse(this.editData.components);
          if (comData) {
            this.editData.left = comData.left;
            this.editData.content = comData.content;
            this.editData.right = comData.right;
          }
        }
        this.editDialog = true;
        // });
      }

      console.log("this.editData");
      console.log(this.editData);
    },
    /**
     * @name 更新数据
     * @param editData 编辑的数据体
     * @description 调用成功关闭对话框并且刷新表单
     */
    update(editData) {
      if (editData.layout == "Dashboard") {
        editData.components = JSON.stringify({
          left: editData.left,
          content: editData.content,
          right: editData.right
        });
      }
      editData.meta = JSON.stringify({
        isAdmin: editData.isAdmin,
        title: editData.menuName,
        icon: editData.icon,
        isDefault: editData.meta ? JSON.parse(editData.meta).isDefault : false,
        center: editData.position,
        show: editData.meta ? JSON.parse(editData.meta).show : true
      });
      console.log("修改后editData");
      console.log(editData);
      //   return false;
      if (!this.validation()) return;
      this.editLoading = true;
      if (editData.id) {
        updateApi(editData)
          .then(({ code, msg }) => {
            if (code == 200) {
              this.$notified.success({
                message: "更新数据成功"
              });
              // this.$refs?.searchbar.reset();
              this.getList(this.searchData, this.pageInfo);
              this.editDialog = false;
              this.topoDialog = false;
            } else {
              this.$notified.error({
                message: msg
              });
            }
          })
          .finally(() => (this.editLoading = false));
      } else {
        addApi(editData)
          .then(({ code, msg }) => {
            if (code == 200) {
              this.$notified.success({
                message: "新增数据成功"
              });
              this.getList(this.searchData, this.pageInfo);
              this.editDialog = false;
            } else {
              this.$notified.error({
                message: msg
              });
            }
          })
          .finally(() => (this.editLoading = false));
      }
    },
    /**
     * @name 表单验证
     * @description 如果有则在此处写入逻辑
     * @returns {Boolean} 表单验证结果
     */
    validation() {
      return true;
    },
    /**
     * @name 删除数据项
     * @description 成功后会刷新列表
     */
    remove(row) {
      this.listLoading = true;
      removeApi({ menuId: row.id })
        .then(({ code, msg }) => {
          if (code == 200) {
            this.$notified.success({
              message: "删除成功"
            });
            this.getList(this.searchData, this.pageInfo);
          } else {
            this.$notified.error({
              message: msg
            });
          }
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    delectMenu(row) {
      this.$confirm("确认删除当前菜单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.remove(row);
        })
        .catch(() => {
          this.$notified({
            message: "已取消删除"
          });
        });
    },
    /**
     * @name 重置表单数据
     */
    reset() {
      this?.editFormInstance?.resetFields();
    },
    handleTreeNodeClick(e) {},
    lock(item) {
      this.editData = item;
      if (item.topoId) {
        this.topoShowList = item.topoId.split(",");
        this.editData.topoId = item.topoId;
      } else {
        this.topoShowList = [];
      }
      this.$nextTick(() => {
        this.topoDialog = true;
      });
    },
    addMenu() {
      this.editDialog = true;
      this.editData.id = "";
      this.editData.parent = "";
    },
    edirtMenu() {}
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
#idName {
  position: relative;
  overflow: hidden;
}
</style>
